// import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'dart:async';

// import '../utils/Builder.dart' as bd;

class MsgPush extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return PushState();
  }
}

class PushState extends State<MsgPush> {
  String debugLable = 'Unknown';
  final JPush jpush = new JPush();

  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;

    try {
      jpush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
        print("flutter onReceiveNotification: $message");
        setState(() {
          debugLable = "flutter onReceiveNotification: $message";
        });
      }, onOpenNotification: (Map<String, dynamic> message) async {
        print("flutter onOpenNotification: $message");
        setState(() {
          debugLable = "flutter onOpenNotification: $message";
        });
        // 弹出对话框
        showDialog(
            context: context,
            builder: (context) => SimpleDialog(
                  title: Text(message['title']),
                  children: <Widget>[
                    Container(
                      child: Text(message['alert']),
                      padding: EdgeInsets.all(20),
                    ),
                    Container(
                      child: TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                          jpush.setBadge(0);
                        },
                        child: Text(
                          '确定',
                          style: TextStyle(color: Colors.white),
                        ),
                        style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.all(Colors.blue),
                        ),
                      ),
                      padding: EdgeInsets.all(20),
                    )
                  ],
                ));
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        print("flutter onReceiveMessage: $message");
        setState(() {
          debugLable = "flutter onReceiveMessage: $message";
        });
      }, onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {
        print("flutter onReceiveNotificationAuthorization: $message");
        setState(() {
          debugLable = "flutter onReceiveNotificationAuthorization: $message";
        });
      });
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    jpush.setup(
      appKey: "c11319ed17e66cd847c16af9", //你自己应用的 AppKey
      channel: "theChannel",
      production: false,
      debug: true,
    );
    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));

    // Platform messages may fail, so we use a try/catch PlatformException.
    jpush.getRegistrationID().then((rid) {
      print("flutter get registration id : $rid");
      setState(() {
        debugLable = "flutter getRegistrationID: $rid";
      });
    });

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      debugLable = platformVersion;
    });
  }

  Widget build(BuildContext context) {
    return Center(
      child: Flex(
        direction: Axis.vertical,
        children: [
          Wrap(
            children: [
              Text('状态：'),
              Text(debugLable ?? ''),
            ],
          ),
          Container(
            child: FlatButton(
              child: Text(
                '测试本地推送',
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                print('本地推送');
                // 1秒后出发本地推送
                var fireDate = DateTime.fromMillisecondsSinceEpoch(
                    DateTime.now().millisecondsSinceEpoch + 1000);
                var localNotification = LocalNotification(
                  id: Random().nextInt(3000),
                  title: '推送测试',
                  buildId: Random().nextInt(9999),
                  content: '推送内容',
                  fireTime: fireDate,
                  subtitle: '子标题',
                  badge: 5,
                  // extra:
                );

                jpush.sendLocalNotification(localNotification).then((res) {
                  setState(() {
                    debugLable = res;
                  });
                });
              },
              color: Colors.blue,
            ),
          )
        ],
      ),
    );
  }
}
